import { ref, computed } from 'vue';
import { defineStore } from 'pinia';
import consultApi from '@/api/consult';

// 数字人状态类型
export const DIGITAL_HUMAN_EMOTIONS = {
  NORMAL: 'normal',
  SMILE: 'smile',
  CONCERNED: 'concerned',
  LISTENING: 'listening'
};

export const DIGITAL_HUMAN_ACTIONS = {
  IDLE: 'idle',
  SPEAKING: 'speaking',
  WAVING: 'waving'
};

// 消息类型
export const MESSAGE_TYPES = {
  USER: 'user',
  SYSTEM: 'system'
};

export const useConsultStore = defineStore('consult', () => {
  // 状态
  const messages = ref([]); // 对话消息列表
  const currentStep = ref(1); // 当前问诊步骤
  const totalSteps = ref(5); // 总问诊步骤
  const isRecording = ref(false); // 是否正在录音
  const recordingTime = ref(0); // 录音时长（秒）
  const isLoading = ref(false); // 是否正在加载
  const isConnected = ref(true); // 连接状态
  const departmentRecommendations = ref([]); // 科室推荐列表
  const examinationRecommendations = ref([]); // 检查项目推荐列表
  
  // 数字人状态
  const digitalHumanEmotion = ref(DIGITAL_HUMAN_EMOTIONS.NORMAL);
  const digitalHumanAction = ref(DIGITAL_HUMAN_ACTIONS.IDLE);
  
  // 计算属性
  const progressPercentage = computed(() => (currentStep.value / totalSteps.value) * 100);
  const hasMessages = computed(() => messages.value.length > 0);
  
  // 方法
  
  // 添加消息
  const addMessage = (type, content, isVoice = false, recommendData = null) => {
    const message = {
      id: Date.now() + Math.random().toString(36).substr(2, 9),
      type,
      content,
      isVoice,
      time: new Date(),
      recommendData
    };
    messages.value.push(message);
    
    // 根据消息内容调整数字人表情
    if (type === MESSAGE_TYPES.USER) {
      analyzeMessageForEmotion(content);
    }
  };
  
  // 分析消息内容调整数字人表情
  const analyzeMessageForEmotion = (content) => {
    const painKeywords = ['痛', '疼', '难受', '不舒服', '绞痛', '刺痛', '胀痛'];
    const hasPain = painKeywords.some(keyword => content.includes(keyword));
    
    if (hasPain) {
      setDigitalHumanState(DIGITAL_HUMAN_EMOTIONS.CONCERNED, DIGITAL_HUMAN_ACTIONS.IDLE);
    } else {
      setDigitalHumanState(DIGITAL_HUMAN_EMOTIONS.SMILE, DIGITAL_HUMAN_ACTIONS.IDLE);
    }
  };
  
  // 设置数字人状态
  const setDigitalHumanState = (emotion, action) => {
    digitalHumanEmotion.value = emotion;
    digitalHumanAction.value = action;
  };
  
  // 开始录音
  const startRecording = () => {
    isRecording.value = true;
    recordingTime.value = 0;
    setDigitalHumanState(DIGITAL_HUMAN_EMOTIONS.LISTENING, DIGITAL_HUMAN_ACTIONS.IDLE);
    
    // 模拟录音计时
    const timer = setInterval(() => {
      if (isRecording.value) {
        recordingTime.value++;
        // 60秒超时自动停止
        if (recordingTime.value >= 60) {
          stopRecording();
        }
      } else {
        clearInterval(timer);
      }
    }, 1000);
  };
  
  // 停止录音
  const stopRecording = () => {
    isRecording.value = false;
    setDigitalHumanState(DIGITAL_HUMAN_EMOTIONS.NORMAL, DIGITAL_HUMAN_ACTIONS.IDLE);
    
    // 模拟语音识别
    if (recordingTime.value > 0) {
      simulateVoiceRecognition();
    }
    
    recordingTime.value = 0;
  };
  
  // 模拟语音识别
  const simulateVoiceRecognition = () => {
    // 模拟识别结果
    const mockResults = [
      '我最近感觉头痛，还有点发烧。',
      '胃痛已经持续三天了，吃东西后更严重。',
      '咳嗽很厉害，喉咙也很痛。',
      '眼睛很干涩，看东西有点模糊。',
      '肩膀很酸，抬不起来。'
    ];
    
    const randomResult = mockResults[Math.floor(Math.random() * mockResults.length)];
    
    // 模拟识别延迟
    setTimeout(() => {
      addMessage(MESSAGE_TYPES.USER, randomResult, true);
      // 模拟系统回复
      simulateSystemResponse(randomResult);
    }, 1000);
  };
  
  // 提交文字消息
  const submitTextMessage = async (content) => {
    if (!content.trim() || isLoading.value) return;
    
    // 添加用户消息
    addMessage(MESSAGE_TYPES.USER, content.trim());
    
    // 模拟系统处理
    await simulateSystemResponse(content.trim());
  };
  
  // 模拟系统回复
  const simulateSystemResponse = async (userMessage) => {
    isLoading.value = true;
    setDigitalHumanState(DIGITAL_HUMAN_EMOTIONS.NORMAL, DIGITAL_HUMAN_ACTIONS.SPEAKING);
    
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // 根据用户问题生成不同的回复
      let systemResponse = '';
      let recommendData = null;
      
      // 关键词匹配
      if (userMessage.includes('头痛') || userMessage.includes('发烧')) {
        systemResponse = '您有头痛和发烧的症状，可能是感冒或其他感染引起的。让我了解更多信息。请问您的体温是多少度？'
      } else if (userMessage.includes('胃痛') || userMessage.includes('胃不舒服')) {
        systemResponse = '胃痛可能与消化系统有关。请问您的疼痛是持续性的还是间歇性的？'
        if (currentStep.value === totalSteps.value) {
          // 最后一步给出科室推荐
          recommendData = await getDepartmentRecommendations('消化');
        }
      } else if (userMessage.includes('咳嗽') || userMessage.includes('喉咙')) {
        systemResponse = '咳嗽和喉咙痛通常与呼吸系统有关。请问您是否有痰？痰是什么颜色的？'
      } else {
        systemResponse = '感谢您的描述。为了更准确地为您推荐科室，能请您详细描述一下症状的频率和持续时间吗？'
      }
      
      // 添加系统回复
      addMessage(MESSAGE_TYPES.SYSTEM, systemResponse, false, recommendData);
      
      // 更新步骤
      if (currentStep.value < totalSteps.value) {
        currentStep.value++;
      }
      
      // 如果有科室推荐，保存到状态
      if (recommendData) {
        departmentRecommendations.value = recommendData.departments || [];
        examinationRecommendations.value = recommendData.examinations || [];
      }
      
    } catch (error) {
      console.error('系统回复失败:', error);
      addMessage(MESSAGE_TYPES.SYSTEM, '很抱歉，我暂时无法为您提供回复，请稍后再试。');
    } finally {
      isLoading.value = false;
      setDigitalHumanState(DIGITAL_HUMAN_EMOTIONS.SMILE, DIGITAL_HUMAN_ACTIONS.IDLE);
    }
  };
  
  // 获取科室推荐（模拟）
  const getDepartmentRecommendations = async (symptomKeyword) => {
    try {
      // 根据症状关键词返回不同的推荐
      let departments = [];
      let examinations = [];
      
      if (symptomKeyword.includes('消化')) {
        departments = [
          {
            id: 1,
            name: '消化内科',
            score: 92,
            reason: '您的胃痛、消化不良症状与消化内科高度匹配',
            queueTime: '约25分钟',
            specialties: '胃炎、胃溃疡、消化不良',
            isTop: true
          },
          {
            id: 2,
            name: '普通外科',
            score: 78,
            reason: '部分胃部疾病可能需要外科干预',
            queueTime: '约40分钟',
            specialties: '腹部外科疾病、疝气',
            isTop: false
          },
          {
            id: 3,
            name: '中医科',
            score: 70,
            reason: '中医调理对慢性肠胃问题有较好效果',
            queueTime: '约30分钟',
            specialties: '脾胃调理、中医针灸',
            isTop: false
          }
        ];
        
        examinations = [
          {
            id: 1,
            name: '胃镜检查',
            purpose: '详细检查胃黏膜情况，明确是否有炎症、溃疡等病变',
            notes: '检查前需空腹6-8小时'
          },
          {
            id: 2,
            name: '幽门螺杆菌检测',
            purpose: '检测是否存在幽门螺杆菌感染，这是胃炎、胃溃疡的常见病因',
            notes: '检查前无需特殊准备'
          }
        ];
      } else if (symptomKeyword.includes('呼吸')) {
        // 其他症状的推荐...
      }
      
      return { departments, examinations };
    } catch (error) {
      console.error('获取科室推荐失败:', error);
      return { departments: [], examinations: [] };
    }
  };
  
  const resetConsult = () => {
    messages.value = [];
    currentStep.value = 1;
    isRecording.value = false;
    recordingTime.value = 0;
    isLoading.value = false;
    departmentRecommendations.value = [];
    examinationRecommendations.value = [];
    setDigitalHumanState(DIGITAL_HUMAN_EMOTIONS.NORMAL, DIGITAL_HUMAN_ACTIONS.IDLE);
  };

  // 结束会话
  const endConsultation = () => {
    messages.value = [];
    currentStep.value = 1;
    isRecording.value = false;
    recordingTime.value = 0;
    isLoading.value = false;
    departmentRecommendations.value = [];
    examinationRecommendations.value = [];
    setDigitalHumanState(DIGITAL_HUMAN_EMOTIONS.NORMAL, DIGITAL_HUMAN_ACTIONS.IDLE);
  };
  
  // 模拟数字人打招呼
  const greetUser = () => {
    setDigitalHumanState(DIGITAL_HUMAN_EMOTIONS.SMILE, DIGITAL_HUMAN_ACTIONS.WAVING);
    
    // 3秒后恢复正常状态
    setTimeout(() => {
      setDigitalHumanState(DIGITAL_HUMAN_EMOTIONS.NORMAL, DIGITAL_HUMAN_ACTIONS.IDLE);
    }, 3000);
  };
  
  return {
    // 状态
    messages,
    currentStep,
    totalSteps,
    isRecording,
    recordingTime,
    isLoading,
    isConnected,
    departmentRecommendations,
    examinationRecommendations,
    digitalHumanEmotion,
    digitalHumanAction,
    
    // 计算属性
    progressPercentage,
    hasMessages,
    
    // 方法
    addMessage,
    setDigitalHumanState,
    startRecording,
    stopRecording,
    submitTextMessage,
    endConsultation,
    resetConsult,
    greetUser,
    
    // 常量
    DIGITAL_HUMAN_EMOTIONS,
    DIGITAL_HUMAN_ACTIONS,
    MESSAGE_TYPES
  };
});